﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using ThesisSystem.DAL;
using ThesisSystem.Models;
using ThesisSystem.ViewModels;
using System;
using System.Data;

namespace ThesisSystem.Controllers
{
    [Authorize]
    public class MenuController : Controller
    {
        private ThesisSystemEntities db = new ThesisSystemEntities();
        //
        // GET: /Menu/
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Menu/Edit/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id)
        {
            var menuToEdit = db.SysMenus.Find(id);
            ViewBag.ParentID = new SelectList(SearchMenu(menuToEdit.ParentID), "MenuID", "Title", menuToEdit.ParentID);
            return View(menuToEdit);
        }

        //
        // POST: /Menu/Edit/5

        [HttpPost]
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id, SysMenu menuToUpdate)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    menuToUpdate.SortID = menuToUpdate.SortID ?? 999;
                    db.Entry(menuToUpdate).State = EntityState.Modified;
                    db.SaveChanges();
                    return Content("修改成功！");
                }                
            }
            catch{}
            ViewBag.ParentID = new SelectList(SearchMenu(menuToUpdate.ParentID), "MenuID", "Title", menuToUpdate.ParentID);
            return View(menuToUpdate);
        }

        //
        // GET: /Menu/Delete/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            var menuToDelete = db.SysMenus.Find(id);
            return View(menuToDelete);
        }

        //
        // POST: /Menu/Delete/5

        [HttpPost]
        [Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                var menuToDelete = db.SysMenus.Find(id);
                db.Entry(menuToDelete).State = EntityState.Deleted;
                db.SaveChanges();
                return Content("删除成功！");
            }
            catch
            {
                return Content("删除失败！");
            }
        }

        public ActionResult Top()
        {
            var topMenus = db.SysMenus.Where(m => m.ParentID == 0).ToList();
            topMenus = topMenus.Where(m => HasPermission(m)).ToList();
            return View(topMenus);
        }

        //左菜单，id为顶级菜单id,subID为二级菜单ID
        public ActionResult Left(int id, int? subId)
        {
            ////用于保存三四级菜单
            //var menus = new List<Level3Menus>();
            //var tempmenu3 = new Level3Menus();
            //var pStudent=Roles.IsUserInRole("Students");
            //var pTeacher=Roles.IsUserInRole("Teachers");
            //var pAdministrator=Roles.IsUserInRole("Administrators");
            ////所有菜单项
            //var allMenus = db.SysMenus;
            ////保存MenuID为id的所有二级菜单项
            ////var level2Menus = allMenus.Where(m => m.ParentID == id && HasPermission(m)).OrderBy(m => m.SortID).ToList();
            //var level2Menus = from m in allMenus
            //                  where m.ParentID == id && ((pStudent && m.PStudent) || (pTeacher && m.PTeacher) || (pTeacher && m.PAdministrator))
            //                  orderby m.SortID
            //                  select m;
            //if (subId == null)
            //{
            //    //如果参数subID为空，则获取第一组二级菜单ID
            //    subId = level2Menus.ToList()[0].MenuID;
            //}
            ////获取指定subID的三级菜单
            //var level3Menus = from m in allMenus
            //                  where m.ParentID == subId && ((pStudent && m.PStudent) || (pTeacher && m.PTeacher) || (pAdministrator && m.PAdministrator))
            //                  orderby m.SortID
            //                  select m;
            //foreach (var menu3 in level3Menus)
            //{
            //    tempmenu3.Level3MenuTitle = menu3.Title;
            //    tempmenu3.Level4Menus = (from m in allMenus
            //                            where m.ParentID == menu3.MenuID && ((pStudent && m.PStudent) || (pTeacher && m.PTeacher) || (pAdministrator && m.PAdministrator))
            //                            orderby m.SortID
            //                            select m).ToList();
            //    menus.Add(tempmenu3);
            //}
            //ViewBag.Level2Menus = level2Menus;
            //return View(menus);

            //获取所有菜单，并分类
            var allMenus = ListMenu();
            allMenus.Menus1 = allMenus.Menus1.Where(m => m.MenuID == id).ToList();
            allMenus.Menus2 = allMenus.Menus2.Where(m => m.ParentID == id && HasPermission(m)).ToList();
            if (subId == null)
            {
                subId = allMenus.Menus2.ToList()[0].MenuID;
            }
            allMenus.Menus3 = allMenus.Menus3.Where(m => m.ParentID == subId && HasPermission(m)).ToList();
            var menus4ID = new HashSet<int>(allMenus.Menus3.Select(m => m.MenuID));
            allMenus.Menus4 = allMenus.Menus4.Where(m => menus4ID.Contains(m.ParentID) && HasPermission(m)).ToList();
            ViewBag.SubID = subId;
            return View(allMenus);
        }

        /// <summary>
        /// 判断当前用户是否有权限显示此菜单
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
        private bool HasPermission(SysMenu menu)
        {
            if((Roles.IsUserInRole("Students")&&menu.PStudent)||(Roles.IsUserInRole("Teachers")&&menu.PTeacher)||(Roles.IsUserInRole("Administrators")&&menu.PAdministrator))
            {
                return true;
            }
            return false;
        }

        public ActionResult Main()
        {
            return View();
        }

        /// <summary>
        /// 查看当前用户所在的用户组
        /// </summary>
        /// <returns></returns>
        //private string[] GetMenuWithRoles()
        //{
        //    string [] roles = new string[] { "0", "0", "0" };
        //    if (Roles.IsUserInRole("Administrators"))
        //    {
        //        roles[2] = "3";
        //    }
        //    if (Roles.IsUserInRole("Teachers"))
        //    {
        //        roles[1] = "2";
        //    }
        //    if (Roles.IsUserInRole("Students"))
        //    {
        //        roles[0] = "1";
        //    }
        //    return roles;
        //}

        [Authorize(Roles="Administrators")]
        public ActionResult Manager()
        {
            return View();
        }

        public ActionResult MenuList()
        {
            var menus = ListMenu();
            return View(menus);
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="menuLevel">要添加的菜单级别</param>
        /// <returns></returns>
        public ActionResult Create(int menuLevel)
        {
            var menus=ListMenu();
            switch (menuLevel)
            {
                case 1:
                    break;
                case 2:
                    ViewBag.ParentID = new SelectList( menus.Menus1,"MenuID","Title");
                    break;
                case 3:
                    ViewBag.ParentID = new SelectList(menus.Menus2, "MenuID", "Title");
                    break;
                case 4:
                    ViewBag.ParentID = new SelectList(menus.Menus3, "MenuID", "Title");
                    break;
            }
            return View(new SysMenu());
        }

        [HttpPost]
        public ActionResult Create(int menuLevel,SysMenu menuToCreate,bool PStudent,bool PTeacher,bool PAdministrator)
        {
            if (ModelState.IsValid)
            {
                if (menuLevel == 1)
                {
                    menuToCreate.ParentID = 0;
                }
                db.SysMenus.Add(menuToCreate);
                db.SaveChanges();
                return RedirectToAction("CreateSucced");
            }
            return Content("failed");
        }

        public ActionResult CreateSucced()
        {
            return View();
        }

        /// <summary>
        /// 根据menuID查询所在级别菜单记录
        /// </summary>
        /// <param name="menuID"></param>
        /// <returns></returns>
        private List<SysMenu> SearchMenu(int menuID)
        {
            var allMenus = ListMenu();
            var menu1 = new HashSet<int>(allMenus.Menus1.Select(m => m.MenuID));
            if (menu1.Contains(menuID))
            {
                return allMenus.Menus1;
            }
            var menu2 = new HashSet<int>(allMenus.Menus2.Select(m => m.MenuID));
            if (menu2.Contains(menuID))
            {
                return allMenus.Menus2;
            }
            var menu3 = new HashSet<int>(allMenus.Menus3.Select(m => m.MenuID));
            if (menu3.Contains(menuID))
            {
                return allMenus.Menus3;
            }
            var menu4 = new HashSet<int>(allMenus.Menus4.Select(m => m.MenuID));
            if (menu4.Contains(menuID))
            {
                return allMenus.Menus4;
            }
            return new List<SysMenu>();
        }

        /// <summary>
        /// 遍历菜单
        /// </summary>
        /// <returns>一到四级菜单</returns>
        private Menus ListMenu()
        {
            var allMenus = db.SysMenus;
            //顶级菜单
            Menus menus = new Menus();
            menus.Menus1 = allMenus.Where(m => m.ParentID == 0).OrderBy(m => m.SortID).ToList();
            foreach (var menu1 in menus.Menus1)
            {
                ////二级菜单
                //menus.Menus2.AddRange(allMenus.Where(m => m.ParentID == menu1.MenuID).OrderBy(m => m.SortID).ToList());
                //foreach (var menu2 in menus.Menus2)
                //{
                //    //三级菜单
                //    menus.Menus3.AddRange(allMenus.Where(m => m.ParentID == menu2.MenuID).OrderBy(m => m.SortID).ToList());
                //    foreach (var menu3 in menus.Menus3)
                //    {
                //        //四级菜单
                //        menus.Menus4.AddRange(allMenus.Where(m => m.ParentID == menu3.MenuID).OrderBy(m => m.SortID).ToList());
                //    }
                //}
                foreach (var menu2 in allMenus.Where(m => m.ParentID == menu1.MenuID).OrderBy(m => m.SortID).ToList())
                {
                    //二级菜单
                    menus.Menus2.Add(menu2);
                    foreach (var menu3 in allMenus.Where(m => m.ParentID == menu2.MenuID).OrderBy(m => m.SortID).ToList())
                    {
                        //三级菜单
                        menus.Menus3.Add(menu3);
                        foreach (var menu4 in allMenus.Where(m => m.ParentID == menu3.MenuID).OrderBy(m => m.SortID).ToList())
                        {
                            //四级菜单
                            menus.Menus4.Add(menu4);
                        }
                    }
                }
            }
            return menus;
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
